package com.kust.smarhome.background.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kust.smarhome.background.mapper.UserMapper;
import com.kust.smarhome.background.model.User;
import com.kust.smarhome.background.service.IUserService;
import com.kust.smarhome.background.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author iAuzre
 * @since 2021-07-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public User getByUsername(String username) {

        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);

        return userMapper.selectOne(query);
    }

    @Override
    public String getUserAuthorityInfo(Integer userId) {

        User user = userMapper.selectById(userId);

        String authority = "";

        if (redisUtil.hasKey("GrantedAuthority:" + user.getUsername())) {
            authority = (String) redisUtil.get("GrantedAuthority:" + user.getUsername());
        } else {
            if (user.getPower() == 1) {
                String roleCode = "admin";
                authority = roleCode;
            }
        }

        redisUtil.set("GrantedAuthority:" + user.getUsername(), authority, 60 * 60);

        return authority;
    }



}
